﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

#if !WINRT
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
#else

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
#endif

namespace MishraReader.Windows.Controls
{
    [TemplatePart(Name = "PART_AnimatedTabPanel", Type = typeof(AnimatedTabPanel))]
    [TemplatePart(Name = "PART_Contents", Type = typeof(FrameworkElement))]
    public class AnimatedTabControl : TabControl
    {
        private AnimatedTabPanel _animatedTabPanel;
        private FrameworkElement _contents;
        private bool _isLoaded;

        static AnimatedTabControl()
        {
            VisibilityProperty.OverrideMetadata(typeof(AnimatedTabControl), new PropertyMetadata(OnVisibilityPropertyChanged));
        }

        public AnimatedTabControl()
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
                Loaded += AnimatedTabControl_Loaded;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _animatedTabPanel = (AnimatedTabPanel)GetTemplateChild("PART_AnimatedTabPanel");
            _contents = (FrameworkElement)GetTemplateChild("PART_Contents");

            ShowTabs();
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this) == false && _contents != null)
                _contents.BeginStoryboard((Storyboard)Application.Current.Resources["MetroSlideView"]);

            base.OnSelectionChanged(e);
        }

        private void ShowTabs()
        {
            if (_isLoaded && _animatedTabPanel != null && Visibility == Visibility.Visible)
                _animatedTabPanel.StartAnimation();
        }

        private void AnimatedTabControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (_isLoaded == false)
            {
                _isLoaded = true;
                ShowTabs();
            }
        }

        private static void OnVisibilityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var animatedTabControl = (AnimatedTabControl)d;
            animatedTabControl.ShowTabs();
        }
    }
}